var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var app = getApp();
const Upyun = require('../../utils/upyun-wxapp-sdk');
const upyun = new Upyun({
  bucket: util.upyun_bucket,
  operator: util.upyun_opterator,
  getSignatureUrl: util.upyun_getSignUrl
});

Page({

  /**
   * 页面的初始数据
   */
  data: {
    util: util,
    screen_w: 320,

    minHeight: 0,

    uploadImg: [],

    photo_w: 0,
    photo_h: 0,

    serviceImages: [],

    configData: '',
  },

  cuid: '',
  token: "",

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    
    var that = this;
    app.LoginUserInfo(function(res) {
      if(res && res != '-1' && res != '-2'){
        console.log("登录用户信息：", res);
        that.cuid = res.uid;
        that.token = res.token;
        that.getAllUpladedImages();
      }
    });
    var p_w = (app.screen_w - 50) / 3
    this.setData({
      isIphone_x: app.isIphone_x,
      screen_w: app.screen_w,
      screen_h: app.screen_h,
      minHeight: app.screen_h - 40,
      photo_w: p_w,
      photo_h: p_w * 1.5
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    
  },

  //上传商品图片 
  upGoodsloadImgs: function() {
    tt.showLoading({
      title: '图片上传中。。。',
      mask: "true"
    });
    var that = this;
    var photos = that.data.uploadImg;
    var uploadCount = 0;
    var tempFileCount = photos.length;
    for (var photoi = 0; photoi < tempFileCount; photoi++) {
      var imgInfo = photos[photoi];
      var imageSrc = imgInfo.path;
      var imgUrl = '/' + util.upyun_imgRootName + '/' + that.cuid + '/image/' + imgInfo.uploadName;

      upyun.upload({
        localPath: imageSrc,
        remotePath: imgUrl,
        success: function(res) {
          uploadCount++;
          console.log("上传图片结果：", res);
          var resImgInfo = JSON.parse(res.data);
          var resImgUrlPaths = resImgInfo.url.split('/');
          var resImgName = resImgUrlPaths[resImgUrlPaths.length - 1];

          for (var imgIndex = 0; imgIndex < tempFileCount; imgIndex++) {
            var imgPath = photos[imgIndex].uploadName;
            if (imgPath.indexOf(resImgName) >= 0) {
              photos[imgIndex].url = util.upyun_imgHost + resImgInfo.url;
              break;
            }
          }
          if (uploadCount == tempFileCount) {
            that.uploadFinish(photos);
            console.log("图片完整信息：", photos);
          }
        },

        fail: function(errMsg) {
          console.log("图片上传失败：" + that.data.uploadImg, errMsg);
          uploadCount++;
          if (uploadCount == tempFileCount) {
            that.uploadFinish(photos);
          }
        }
      })
    }
  },

  uploadFinish: function(imageInfos) {
    console.log("图片信息：", imageInfos);
    var imageArr = [];
    imageInfos.forEach(function(m, i) {
      imageArr = imageArr.concat(m.url ? m.url : '');
    });
    var that = this;
    var privatekey = utilMd5.hexMD5(that.cuid + 'saveimages' + that.token);
    console.log("图片链接：", imageArr);
    //保存图片信息到服务器
    util.api_go({
      data: {
        "ac": "saveimages",
        "uid": that.cuid,
        "privatekey": privatekey,
        "postuid": that.cuid,
        "images": JSON.stringify(imageArr)
      },
      method: 'POST',
      success: function(responseData) {
        console.log("保存图片链接返回：", responseData);
        if (responseData.data.res) {
          that.getAllUpladedImages(true);
        }
        tt.hideLoading();
      }
    });


  },

  //选择图片
  selectLocalImg: function() {
    var that = this;
    tt.chooseMedia({
      count: 9,
      mediaType: ['image'],
      sizeType: ['compressed'],
      sourceType: ['album'],
      success: function(res) {
        console.log("本地图片信息：", res);
        const tempFiles = res.tempFiles;
        var selImgs = [];
        for (var i = 0; i < tempFiles.length; i++) {
          var imgInfo = {};
          imgInfo.path = tempFiles[i].tempFilePath;
          let houzui = imgInfo.path.substring(imgInfo.path.lastIndexOf('.'), imgInfo.path.length)
          console.log("图片后缀：" + houzui);
          let timeStamp = util.getImgOrVideoName()
          imgInfo.uploadName = timeStamp + '_' + i + houzui;
          console.log("上传的图片名称：" + imgInfo.uploadName);
          selImgs[i] = imgInfo;
        }
        selImgs = that.data.uploadImg.concat(selImgs)
        that.setData({
          uploadImg: selImgs
        })
        // that.upGoodsloadImgs();
      },

      fail: function({
        errMsg
      }) {
        console.log('chooseImage fail, err is', errMsg)
      }
    });
  },

  //获取该用户所有已上传的图片信息
  getAllUpladedImages: function(reget = false) {
    var that = this;
    tt.showLoading({
      title: 'loading...',
      mask: "true"
    });
    app.getAllUpladedImages(that.cuid, reget, function(res){
      if(res != 0 && res != -1) {
        that.setData({
          serviceImages: res,
          uploadImg: []
        })
      } else {
        that.setData({
          serviceImages: []
        })
      }
      tt.hideLoading();
    })
  },

  //删除图片动作
  deleteAction:function(e){
    console.log("删除图片确认：", e)
    var noticeStr = e.currentTarget.dataset.selids != undefined ? "此操作不可恢复，确定删除选中图片吗？" : "确定删除选中图片吗？"
    var that = this;
    tt.showModal({
      title: '提示',
      content: noticeStr,
      success:function(res){
        if(res.confirm){
          if (e.currentTarget.dataset.selindex != undefined) {
            let selIndex = e.currentTarget.dataset.selindex
            console.log("删除本地选择的图片：" + selIndex)
            let localImgArr = that.data.uploadImg
            localImgArr.splice(selIndex, 1);
            that.setData({
              uploadImg: localImgArr
            })
          } else if (e.currentTarget.dataset.selids != undefined) {
            let selIdArr = []
            selIdArr.push(e.currentTarget.dataset.selids)
            console.log("选中的服务器图片id：", selIdArr)
            that.deleteImg(selIdArr);  
          }
        }
      }
    })
  },

  //删除图片 
  deleteImg: function(idArr) {
    var that = this;
    tt.showLoading({
      title: '',
      mask: true
    })
    var privatekey = utilMd5.hexMD5(that.cuid + 'delimage' + that.token);
    //保存图片信息到服务器
    util.api_go({
      data: {
        "ac": "delimage",
        "uid": that.cuid,
        "privatekey": privatekey,
        "postuid": that.cuid,
        "imgids": JSON.stringify(idArr)
      },
      method: 'POST',
      success: function(responseData) {
        tt.hideLoading()
        console.log("删除图片返回：", responseData);
        if (responseData.data.res) {
          tt.showToast({
            title: "删除成功"
          })
          that.getAllUpladedImages(true);
        } else {
          tt.showToast({
            title: responseData.data.msg
          })
        }
      }
    });
  },

  goAtherPage: function(e) {
    var url = e.currentTarget.dataset.link;
    tt.navigateTo({
      url: url
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

})